<?php

/**
 * 购物车相关
 *
 * @author birdy <freebirdy@foxmail.com>
 * @link http://www.aiyuangong.com
 */

namespace app\member\controller;

class Cart extends \app\common\controller\Member
{
    /**
     * 购物车列表
     */
    public function index()
    {
        $this->assign('step', 'step1');

        $logic_buy_1 = model('Common/Buy1', 'logic');

        //购物车列表
        $cart_list = $this->listCart('db', array('buyer_id' => $this->member_id));

        if ($cart_list) {
            //购物车列表 [得到最新商品属性及促销信息] 
            $cart_list = $logic_buy_1->getGoodsCartList($cart_list);

            //购物车商品以店铺ID分组显示,并计算商品小计,店铺小计与总价由JS计算得出
            $store_cart_list = array();
            foreach ($cart_list as $cart) {
                $cart['goods_total'] = ncPriceFormat($cart['goods_price'] * $cart['goods_num']);
                $store_cart_list[$cart['store_id']][] = $cart;
            }
            $this->assign('store_cart_list', $store_cart_list);

            //店铺信息
            $store_list = $this->db_lists('store', ['id' => ['in', array_keys($store_cart_list)]], ['field' => 'id,member_id,store_domain']);
            $this->assign('store_list', $store_list);

            //to do 取得店铺级活动 - 可用的满即送活动
            $this->assign('mansong_rule_list', []);

            //取得哪些店铺有满免运费活动
            $free_freight_list = $logic_buy_1->getFreeFreightActiveList(array_keys($store_cart_list));
            $this->assign('free_freight_list', $free_freight_list);
        }

        //标识 购买流程执行第几步

        return view(empty($cart_list) ? 'cart_empty' : 'index');
    }
    
    /**
     * 异步查询购物车
     */
    public function ajax_load()
    {
        $cart_goods_num = 0;
        $cart_all_price = 0;
        if ($this->member_id > 0) {
            //登录后
            $cart_list = $this->listCart('db', array('buyer_id' => $this->member_id));
            $cart_array = array();
            if (!empty($cart_list)) {
                foreach ($cart_list as $k => $cart) {
                    $cart_array['list'][$k]['cart_id'] = $cart['cart_id'];
                    $cart_array['list'][$k]['goods_id'] = $cart['goods_id'];
                    $cart_array['list'][$k]['goods_name'] = $cart['goods_name'];
                    $cart_array['list'][$k]['goods_price'] = $cart['goods_price'];
                    $cart_array['list'][$k]['goods_image'] = img_url($cart['goods_image'], 60);
                    $cart_array['list'][$k]['goods_num'] = $cart['goods_num'];
                    $cart_array['list'][$k]['goods_url'] = url('index/goods/detail', array('goods_id' => $cart['goods_id']));
                    $cart_all_price += $cart['goods_price'] * $cart['goods_num'];
                }
                $cart_goods_num = count($cart_list);
            }
        } else {
            //登录前
            $cart_list = $this->listCart('cookie');
            foreach ($cart_list as $key => $cart) {
                $value = array();
                $value['cart_id'] = $cart['goods_id'];
                $value['goods_name'] = $cart['goods_name'];
                $value['goods_price'] = $cart['goods_price'];
                $value['goods_num'] = $cart['goods_num'];
                $value['goods_image'] = img_url($cart['goods_image'], 60);
                $value['goods_url'] = url('index/goods/detail', array('goods_id' => $cart['goods_id']));
                $cart_all_price += $cart['goods_price'] * $cart['goods_num'];
                $cart_array['list'][] = $value;
            }
            $cart_goods_num = count($cart_list);
        }
        cookie('cart_goods_num', $cart_goods_num, 2 * 3600);
        $cart_array['cart_all_price'] = ncPriceFormat($cart_all_price);
        $cart_array['cart_goods_num'] = $cart_goods_num;
        if (input('type') == 'html') {
            $this->assign('cart_list', $cart_array);
            return view('cart_mini');
        } else {
            if (input('callback')) {
                return jsonp($cart_array);
            } 
            return json($cart_array);
        }
    }

    /**
     * 添加购物车
     */
    public function add()
    {
        $goods_id = input('goods_id/d');
        if ($goods_id > 0) {
            //商品加入购物车(默认)
            $quantity = input('quantity/d', 1);
            $goods_info = $this->getGoodsOnlineInfoAndPromotionById($goods_id);

            //to do 抢购
            //to do 限时折扣

            $this->_check_goods($goods_info, $quantity);
        } else {
            return $this->error('商品不存在');
        }

        //已登录状态，存入数据库,未登录时，存入COOKIE
        if ($this->member_id > 0) {
            $save_type = 'db';
            $goods_info['buyer_id'] = $this->member_id;
        } else {
            $save_type = 'cookie';
        }

        $insert = $this->addCart($goods_info, $save_type, $quantity);
        if ($insert) {
            //购物车商品种数记入cookie
            $cart_goods = $this->getCartNum($save_type, array('buyer_id' => $goods_info['buyer_id']));
            $data = array('status' => 'true', 'num' => $cart_goods['num'], 'amount' => ncPriceFormat($cart_goods['money']));
        } else {
            $data = array('status' => 'false');
        }

        return json($data);
    }

    /**
     * 更新数量
     */
    public function update()
    {
        $cart_id = input('cart_id/d');
        $quantity = input('quantity/d');

        if (empty($cart_id) || empty($quantity) || $quantity < 1) {
            return json(array('status'=>'','msg' => '修改失败'));
        }

        $logic_buy_1 = model('Common/Buy1', 'logic');
        $queue = model('Common/Queue', 'logic');

        //存放返回信息
        $return = array();

        $cart_info = rpc('common/common/one', ['cart', ['cart_id' => $cart_id, 'buyer_id' => $this->member_id]]);
        if ($cart_info['bl_id'] == '0') {
            //普通商品
            $goods_id = intval($cart_info['goods_id']);
            $goods_info = $logic_buy_1->getGoodsOnlineInfo($goods_id, $quantity);
            if (empty($goods_info)) {
                $return['status'] = 'invalid';
                $return['msg'] = '商品已被下架';
                $return['subtotal'] = 0;
                $queue->delCart(['buyer_id' => $this->member_id, 'cart_ids' => array($cart_id)]);
                return json($return);
            }

            //to do 抢购
            //to do 限时折扣

            $quantity = $goods_info['goods_num'];

            if (intval($goods_info['goods_storage']) < $quantity) {
                $return['status'] = 'shortage';
                $return['msg'] = '库存不足';
                $return['goods_num'] = $goods_info['goods_num'];
                $return['goods_price'] = $goods_info['goods_price'];
                $return['subtotal'] = $goods_info['goods_price'] * $quantity;
                rpc('common/common/update', ['cart', ['cart_id' => $cart_id, 'buyer_id' => $this->member_id], ['goods_num' => $goods_info['goods_storage']]]);
                return json($return);
            }
        }

        $data = array();
        $data['goods_num'] = $quantity;
        $data['goods_price'] = $goods_info['goods_price'];
        $update = rpc('common/common/update', ['cart', ['cart_id' => $cart_id, 'buyer_id' => $this->member_id], $data]);
        if ($update !== false) {
            $return = array();
            $return['status'] = 'true';
            $return['subtotal'] = $goods_info['goods_price'] * $quantity;
            $return['goods_price'] = $goods_info['goods_price'];
            $return['goods_num'] = $quantity;
            return json($return);
        } else {
            return json(array('status'=>'','msg' => '修改失败'));
        }
    }

    public function del()
    {
        $cart_id = input('cart_id/d');
        if ($cart_id < 0) {
            return;
        }

        $data = array();
        if ($this->member_id > 0) {
            //登录状态下删除数据库内容
            $delete = $this->delCart('db', array('cart_id' => $cart_id, 'buyer_id' => $this->member_id));
            if ($delete) {
                $data['status'] = 'true';
                $data['quantity'] = $delete['num'];
                $data['amount'] = $delete['money'];
            } else {
                $data['msg'] = '商品删除失败';
            }
        } else {
            //未登录时删除cookie的购物车信息
            $delete = $this->delCart('cookie', array('goods_id' => $cart_id));
            if ($delete) {
                $data['status'] = 'true';
                $data['quantity'] = $delete['num'];
                $data['amount'] = $delete['money'];
            }
        }

        if (isset($_GET['callback'])) {
            return jsonp($data);
        }

        return json($data);
    }

    /**
     * 将商品添加到购物车中
     *
     * @param array	$data	商品数据信息
     * @param string $save_type 保存类型，可选值 db,cookie
     * @param int $quantity 购物数量
     */
    private function addCart($data = array(), $save_type = '', $quantity = null)
    {
        $method = '_addCart' . ucfirst($save_type);
        $insert = $this->$method($data, $quantity);
        //更改购物车总商品数和总金额，传递数组参数只是给DB使用
        return $insert;
    }

    /**
     * 添加数据库购物车
     *
     * @param unknown_type $goods_info
     * @param unknown_type $quantity
     * @return unknown
     */
    private function _addCartDb($goods_info = array(), $quantity)
    {
        //验证购物车商品是否已经存在
        $condition = array();
        $condition['goods_id'] = $goods_info['goods_id'];
        $condition['buyer_id'] = $goods_info['buyer_id'];
        if (isset($goods_info['bl_id'])) {
            $condition['bl_id'] = $goods_info['bl_id'];
        } else {
            $condition['bl_id'] = 0;
        }
        ;
        $check_cart = $this->checkCart($condition);
        if (!empty($check_cart)) {
            return true;
        }

        $array = array();
        $array['buyer_id'] = $goods_info['buyer_id'];
        $array['store_id'] = $goods_info['store_id'];
        $array['goods_id'] = $goods_info['goods_id'];
        $array['goods_name'] = $goods_info['goods_name'];
        $array['goods_price'] = $goods_info['goods_price'];
        $array['goods_num'] = $quantity;
        $array['goods_image'] = $goods_info['goods_image'];
        $array['store_name'] = $goods_info['store_name'];
        $array['bl_id'] = isset($goods_info['bl_id']) ? $goods_info['bl_id'] : 0;
        return rpc("common/common/create", ['cart', $array]);
    }

    /**
     * 添加到cookie购物车,最多保存5个商品
     *
     * @param unknown_type $goods_info
     * @param unknown_type $quantity
     * @return unknown
     */
    private function _addCartCookie($goods_info = array(), $quantity = null)
    {
        //去除斜杠
        $cart_str = get_magic_quotes_gpc() ? stripslashes(cookie('cart')) : cookie('cart');
        $cart_str = base64_decode(decrypt($cart_str));
        $cart_array = @unserialize($cart_str);
        $cart_array = !is_array($cart_array) ? array() : $cart_array;
        if (count($cart_array) >= 5) {
            return false;
        }

        if (in_array($goods_info['goods_id'], array_keys($cart_array))) {
            return true;
        }
        $cart_array[$goods_info['goods_id']] = array(
            'store_id' => $goods_info['store_id'],
            'goods_id' => $goods_info['goods_id'],
            'goods_name' => $goods_info['goods_name'],
            'goods_price' => $goods_info['goods_price'],
            'goods_image' => $goods_info['goods_image'],
            'goods_num' => $quantity
        );
        cookie('cart', encrypt(base64_encode(serialize($cart_array))), 24 * 3600);
        return true;
    }

    /**
     * 检查购物车内商品是否存在
     *
     * @param
     */
    public function checkCart($condition = array())
    {
        return rpc("common/common/total", ['cart', $condition]);
    }

    /**
     * 购物车列表
     *
     * @param string $type 存储类型 db,cookie
     * @param unknown_type $condition
     * @param int $limit
     */
    private function listCart($type, $condition = array())
    {
        if ($type == 'db') {
            $cart_list = rpc('common/common/lists', ['cart', $condition]);
        } elseif ($type == 'cookie') {
            //去除斜杠
            $cart_str = get_magic_quotes_gpc() ? stripslashes(cookie('cart')) : cookie('cart');
            $cart_str = base64_decode(decrypt($cart_str));
            $cart_list = @unserialize($cart_str);
        }

        $cart_list = is_array($cart_list) ? $cart_list : array();
        return !is_array($cart_list) ? array() : $cart_list;
    }

    /**
     * 删除购物车商品
     *
     * @param string $type 存储类型 db,cookie
     * @param unknown_type $condition
     */
    public function delCart($type, $condition = array())
    {
        if ($type == 'db') {
            $result = rpc('common/common/delete', ['cart', $condition]);
        } elseif ($type == 'cookie') {
            $cart_str = get_magic_quotes_gpc() ? stripslashes(cookie('cart')) : cookie('cart');
            $cart_str = base64_decode(decrypt($cart_str));
            $cart_array = @unserialize($cart_str);
            if (key_exists($condition['goods_id'], (array) $cart_array)) {
                unset($cart_array[$condition['goods_id']]);
            }
            cookie('cart', encrypt(base64_encode(serialize($cart_array))), 24 * 3600);
            $result = true;
        }

        //重新计算购物车商品数和总金额
        if ($result) {
            return $this->getCartNum($type, array('buyer_id' => $condition['buyer_id']));
        }
        return $result;
    }

    /**
     * 计算购物车总商品数和总金额
     * @param string $type 购物车信息保存类型 db,cookie
     * @param array $condition 只有登录后操作购物车表时才会用到该参数
     */
    private function getCartNum($type, $condition = array())
    {
        if ($type == 'db') {
            $cart_all_price = 0;
            $cart_goods = $this->db_lists('cart', $condition);
            $cart_goods_num = count($cart_goods);
            if (!empty($cart_goods) && is_array($cart_goods)) {
                foreach ($cart_goods as $val) {
                    $cart_all_price += $val['goods_price'] * $val['goods_num'];
                }
            }
            $cart_all_price = ncPriceFormat($cart_all_price);
        } elseif ($type == 'cookie') {
            $cart_str = get_magic_quotes_gpc() ? stripslashes(cookie('cart')) : cookie('cart');
            $cart_str = base64_decode(decrypt($cart_str));
            $cart_array = @unserialize($cart_str);
            $cart_array = !is_array($cart_array) ? array() : $cart_array;
            $cart_goods_num = count($cart_array);
            $cart_all_price = 0;
            foreach ($cart_array as $v) {
                $cart_all_price += floatval($v['goods_price']) * intval($v['goods_num']);
            }
            $cart_all_price = $cart_all_price;
        }
        cookie('cart_goods_num', $cart_goods_num, 2 * 3600);
        return ['num' => $cart_goods_num, 'money' => $cart_all_price];
    }

    /**
     * 查询出售中的商品详细信息及其促销信息
     * @param int $goods_id
     * @return array
     */
    private function getGoodsOnlineInfoAndPromotionById($goods_id)
    {
        $goods_info = $this->getGoodsInfoAndPromotionById($goods_id);
        if (empty($goods_info) || $goods_info['goods_state'] != GOODS_STATE_ON || $goods_info['goods_verify'] != GOODS_VERIFY_PASS) {
            return array();
        }
        return $goods_info;
    }

    /**
     * 查询商品详细信息及其促销信息
     * @param int $goods_id
     * @return array
     */
    private function getGoodsInfoAndPromotionById($goods_id)
    {
        $goods_info = rpc('common/common/one', ['goods', ['id' => $goods_id]]);
        if (empty($goods_info)) {
            return array();
        }

        $goods_info['goods_id'] = $goods_info['id'];

        //to do 抢购
        $goods_info['groupbuy_info'] = [];

        //to do 限时折扣
        $goods_info['xianshi_info'] = [];

        return $goods_info;
    }

    /**
     * 检查商品是否符合加入购物车条件
     * @param unknown $goods
     * @param number $quantity
     */
    private function _check_goods($goods_info, $quantity)
    {
        if (empty($quantity)) {
            return $this->error('参数不正确');
        }
        if (empty($goods_info)) {
            return $this->error('该商品不存在');
        }
        if ($goods_info['store_id'] == $this->store_id) {
            return $this->error('不能购买自己店铺的商品');
        }
        if (intval($goods_info['goods_storage']) < 1) {
            return $this->error('商品库存不足，暂时无法购买');
        }
        if (intval($goods_info['goods_storage']) < $quantity) {
            return $this->error('库存不足');
        }
        if ($goods_info['is_virtual'] || $goods_info['is_fcode'] || $goods_info['is_presell']) {
            return $this->error('该商品不允许加入购物车，请直接购买');
        }
    }

}
